import { useEffect, useState } from 'react';
import NetInfo from '@react-native-community/netinfo';
import DeviceInfo from 'react-native-device-info';
import { saveValue } from './asyncStorage';

const inititalState = {
  net_type: null, // wifi 2/3/4g
  carrier: null,
  isConnected: false,
  ifChange: false,
};

const useDeviceAndNetInfo = () => {
  const [deviceNetInfo, setDeviceNetInfo] = useState(inititalState);

  const saveAndReturnNetInfo = async (connectionInfo) => {
    const newNetInfo = {
      net_type: connectionInfo.type,
    };
    if (newNetInfo.net_type === 'cellular') {
      newNetInfo.net_type = connectionInfo.details.cellularGeneration;
      newNetInfo.carrier = connectionInfo.details.carrier;
    }
    await saveValue('netinfo', newNetInfo);
    newNetInfo.isConnected = connectionInfo.isConnected;
    return newNetInfo;
  };
  const onChangeNetInfo = async (connectionInfo) => {
    const newNetInfo = await saveAndReturnNetInfo(connectionInfo);
    setDeviceNetInfo({ ...deviceNetInfo, ...newNetInfo, ifchange: true });
  };

  useEffect(() => {
    let didCancel = false;
    let unsubscriber;
    async function saveDeviceNetInfo() {
      const connectionInfo = await NetInfo.fetch();
      const [apiLevel, macAddr, manufacturer] = await Promise.all([
        DeviceInfo.getApiLevel(),
        DeviceInfo.getMacAddress(),
        DeviceInfo.getManufacturer(),
      ]);
      let deviceToken;
      try {
        deviceToken = await DeviceInfo.getDeviceToken();
      } catch (err) {
        // iphone simulator exception
      }
      if (!didCancel) {
        const newNetInfo = await saveAndReturnNetInfo(connectionInfo);
        const deviceInfo = {
          api_level: apiLevel, //api版本
          application_name: DeviceInfo.getApplicationName(), //应用名称
          brand: DeviceInfo.getBrand(), //设备品牌
          device_id: DeviceInfo.getDeviceId(), //设备id
          device_token: deviceToken, //ios设备token
          mac_addr: macAddr, //mac地址
          manufacturer, //制造商
          system_os: DeviceInfo.getSystemName(), //os名称
          os_version: DeviceInfo.getSystemVersion(), //os版本号
          unique_id: DeviceInfo.getUniqueId(), //设备唯一id
          app_version: DeviceInfo.getVersion(), //app版本号
        };
        await saveValue('deviceinfo', deviceInfo);
        setDeviceNetInfo({ ...newNetInfo, ...deviceInfo });
        unsubscriber = NetInfo.addEventListener(onChangeNetInfo);
        /*
        if (isAndroid) {
          const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
            {
              title: 'Cool Photo App Camera Permission',
              message:
                'Cool Photo App needs access to your camera ' +
                'so you can take awesome pictures.',
              buttonNeutral: 'Ask Me Later',
              buttonNegative: 'Cancel',
              buttonPositive: 'OK',
            },
          );
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            console.log('You can use location');
          } else {
            console.log('Camera permission denied');
          }
        } else {
          Geolocation.requestAuthorization();
        }
        Geolocation.getCurrentPosition(
          (info) => console.log(info),
          (err) => console.log(err),
          {
            enableHighAccuracy: false,
            timeout: 20000,
            maximumAge: 0,
            distanceFilter: 10,
          },
        );
        */
      }
    }
    saveDeviceNetInfo();
    return () => {
      didCancel = true;
      if (unsubscriber) {
        unsubscriber();
      }
    };
  }, []);

  return deviceNetInfo;
};

export default useDeviceAndNetInfo;
